{% extends "shared/layout.twig" %}
{% block head %}
    {# <meta name="csrf-token" content="{{token}}"> #}
    <link rel="stylesheet" type="text/css" href="/static/admin/js/libs/jquery-ui/themes/smoothness/jquery-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="/static/admin/js/libs/elFinder/css/elfinder.min.css"/>
{% endblock %}
{% block content %}
    <div class="breadcrumb-container">
      <div class="row">
        <div class="col-md">
          <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="#">控制面板</a></li>
              <li class="breadcrumb-item"><a href="/dashboard/pages">页面</a></li>
              <li class="breadcrumb-item active" aria-current="page">
                {{title}}
              </li>
            </ol>
          </nav>
        </div>
        <div class="col-md-auto">
          <time id="sitetime"></time>
        </div>
      </div>
    </div>

    <form novalidate="novalidate" id="editform">
        <div class="card">
            <div class="card-header">
                {{title}}
            </div>
            <div class="card-body">
                {# <input type="hidden" name="__token__" value="{{token}}" /> #}
            {% if (page is defined) and (page is not empty) %}

                <div class="row">
                    <div class="col">
                
                    <input id="id" type="hidden" id='id' name="id" value="{{page.id}}" />
                    {# <input type="hidden" id="action" name="action" value="<?php echo $action; ?>" /> #}
                    <div class="form-group">
                        <label for="title">标题</label>
                        <input type="text" class="form-control" id="title" name="title" placeholder="" value="{{page.title}}">
                    </div>

                    <div class="form-group">
                        <label for="title">别名</label>
                        <input type="text" class="form-control" id="alias" name="alias" value="{{page.alias}}"
                            placeholder="必填">
                    </div>
                    <div class="form-group">
                        <label for="importance">排序</label>
                        <input type="number" class="form-control" id="importance" name="importance" value="{{page.importance}}" placeholder="值越大越排前">
                    </div>

                    <div class="form-group">
                        <label for="content">内容</label>
                        <textarea class="form-control" id="content" name="content" placeholder="">{{page.content|raw}}</textarea>
                        
                    </div>
                
                
                    <div class="form-group">
                        <div class="form-check">
                   
                            <input type="checkbox" class="form-check-input" {{page.active?"checked":""}} id="chkActive" name="active">
                            <label class="form-check-label" for="chkActive">发布</label>
                        </div>
                    </div>

                    </div>
                        <div class="col-auto">
                            <div style="width:300px;  text-align:center;" class="mb-3">
                                <div class="card">
                                    <div class="card-body">                                       
                                        <img ID="iLogo" data-default-src="holder.js/240x180?text=1920X550像素" src="{{page.background_image?"page.background_image":"holder.js/240x180?text=1920X550像素"}}" class="img-fluid" />
                                    </div>
                                    <div class="card-footer">
                                        <button type="button" id="btnBrowser" class="btn btn-info"><i class="fa fa-picture-o"></i> 背景图...</button>
                                        {% if page.background_image|length >0 %}
                                        <button type="button" id="btnImgDelete" class="btn btn-danger"><i class="iconfont icon-delete"></i> 移除</button>
                                        {% endif %}                                     
                                        <input id="background_image" type="hidden" name="background_image" value="{{page.background_image}}" />
                                    </div>
                                </div>
                            </div>
                            {% if metadata is defined %}
                                {% if metadata.name is not empty %}
                                <div class="card">
                                    <div class="card-header">SEO</div>
                                        <div class="card-body">
                                            <div class="form-group">
                                                <label for="title">SEO标题</label>
                                                <input type="text" class="form-control" id="seotitle" name="seotitle" placeholder="" value="{{metadata.title}}">
                                            </div>

                                            <div class="form-group">
                                                <label for="description">SEO描述</label>
                                                <textarea class="form-control" id="seodescription" name="seodescription" rows="6" placeholder="">{{metadata.description}}</textarea>

                                            </div>
                                            <div class="form-group">
                                                <label for="keywords">关键字</label>
                                                <input type="text" class="form-control" id="seokeywords" name="seokeywords" placeholder="" value="{{metadata.keywords}}">
                                            </div>
                                        </div>

                                    </div>
                                
                                </div>
                            {% endif %}
                          {% endif %}
                    </div>

            {% else %}
                <div class="row">
                    <div class="col">
                    <input id="id" type="hidden" id='id' name="id" value="0" />
                    {# <input type="hidden" id="action" name="action" value="<?php echo $action; ?>" /> #}
                    <div class="form-group">
                        <label for="title">标题</label>
                        <input type="text" class="form-control" id="title" name="title" placeholder="">
                    </div>

                    <div class="form-group">
                        <label for="title">别名</label>
                        <input type="text" class="form-control" id="alias" name="alias" 
                            placeholder="必填">
                    </div>
                    <div class="form-group">
                        <label for="importance">排序</label>
                        <input type="number" class="form-control" id="importance" name="importance" value="0" placeholder="值越大越排前">
                    </div>

                    <div class="form-group">
                        <label for="content">内容</label>
                        <textarea class="form-control" id="content" name="content" placeholder=""></textarea>                        
                    </div>
                
                
                    <div class="form-group">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" checked id="chkActive" name="active">
                            <label class="form-check-label" for="chkActive">发布</label>
                        </div>
                    </div>

                    </div>
                        <div class="col-auto">
                            <div style="width:300px;  text-align:center;" class="mb-3">
                                <div class="card">
                                    <div class="card-body">                                       
                                        <img ID="iLogo" data-default-src="holder.js/240x180?text=1920X550像素" src="holder.js/240x180?text=1920X550像素" class="img-fluid" />
                                    
                                    </div>
                                    <div class="card-footer">
                                        <button type="button" id="btnBrowser" class="btn btn-info"><i class="fa fa-picture-o"></i> 背景图...</button>                                     
                                        <input id="background_image" type="hidden" name="background_image" />
                                    </div>
                                </div>
                            </div>
                            <div class="card">
                                <div class="card-header">SEO</div>
                                <div class="card-body">
                                    <div class="form-group">
                                        <label for="title">SEO标题</label>
                                        <input type="text" class="form-control" id="seotitle" name="seotitle" placeholder="">
                                    </div>

                                    <div class="form-group">
                                        <label for="description">SEO描述</label>
                                        <textarea class="form-control" id="seodescription" name="seodescription" rows="6" placeholder=""></textarea>

                                    </div>
                                    <div class="form-group">
                                        <label for="keywords">关键字</label>
                                        <input type="text" class="form-control" id="seokeywords" name="seokeywords" placeholder="">

                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>

            {% endif %}
               
                

            </div>
            <div class="card-footer text-center">

                <button type="submit" class="btn btn-primary"><i class="iconfont icon-save"></i> 保存</button>
                <a href="JavaScript:window.history.back()" class="btn btn-outline-secondary"><i class="iconfont icon-left"></i> 返回</a>

            </div>
        </div>
    </form>
    
{% endblock %}

{% block footer %}
    <script src="/static/admin/js/libs/holderjs/holder.min.js"></script>
    <script src="/static/admin/js/libs/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="/static/admin/js/libs/jquery-validation/dist/additional-methods.min.js"></script>

    <script type="text/javascript" src="/static/admin/js/libs/jquery-ui/jquery-ui.min.js"></script>    

    <script src="/static/admin/js/libs/elFinder/js/elfinder.min.js"></script>
    <script src="/static/admin/js/libs/elFinder/js/i18n/elfinder.zh_CN.js"></script>
    <script src="/static/admin/js/libs/tinymce/tinymce.min.js"></script>
    <script src="/static/admin/js/libs/tinymceElfinder.js"></script>

    <script type="text/javascript">
        const mceElf = new tinymceElfinder({
            // connector URL (Set your connector)
            url: '/static/admin/js/libs/elFinder/php/connector.minimal.php',
            lang: 'zh_CN',
            // upload target folder hash for this tinyMCE
            uploadTargetHash: 'l1_lw', // Hash value on elFinder of writable folder
            // elFinder dialog node id
            nodeId: 'elfinder' // Any ID you decide
        });

        var useDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
        tinymce.init({
            selector: '#content',
            language:'zh_CN',
            plugins: 'print preview paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars emoticons',
            imagetools_cors_hosts: ['picsum.photos'],
            menubar: 'file edit view insert format tools table help',
            toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | insertfile image media template link anchor codesample | ltr rtl',
            toolbar_sticky: true,
            autosave_ask_before_unload: true,
            autosave_interval: '30s',
            autosave_prefix: '{path}{query}-{id}-',
            autosave_restore_when_empty: false,
            autosave_retention: '2m',
            image_advtab: true,
            link_list: [
                { title: 'My page 1', value: 'https://www.tiny.cloud' },
                { title: 'My page 2', value: 'http://www.moxiecode.com' }
            ],
            image_list: [
                { title: 'My page 1', value: 'https://www.tiny.cloud' },
                { title: 'My page 2', value: 'http://www.moxiecode.com' }
            ],
            image_class_list: [
                { title: 'None', value: '' },
                { title: 'Some class', value: 'class-name' }
            ],
            importcss_append: true,
            file_picker_callback : mceElf.browser,
            images_upload_handler: mceElf.uploadHandlerExt,

            templates: [
                { title: 'New Table', description: 'creates a new table', content: '<div class="mceTmpl"><table width="98%%"  border="0" cellspacing="0" cellpadding="0"><tr><th scope="col"> </th><th scope="col"> </th></tr><tr><td> </td><td> </td></tr></table></div>' },
                { title: 'Starting my story', description: 'A cure for writers block', content: 'Once upon a time...' },
                { title: 'New list with dates', description: 'New List with dates', content: '<div class="mceTmpl"><span class="cdate">cdate</span><br /><span class="mdate">mdate</span><h2>My List</h2><ul><li></li><li></li></ul></div>' }
            ],
            template_cdate_format: '[Date Created (CDATE): %m/%d/%Y : %H:%M:%S]',
            template_mdate_format: '[Date Modified (MDATE): %m/%d/%Y : %H:%M:%S]',
            height: 600,
            image_caption: true,
            quickbars_selection_toolbar: 'bold italic | quicklink h2 h3 blockquote quickimage quicktable',
            noneditable_noneditable_class: 'mceNonEditable',
            toolbar_mode: 'sliding',
            contextmenu: 'link image imagetools table',
            skin: useDarkMode ? 'oxide-dark' : 'oxide',
           // content_css:  '/bbi-admin/assets/js/bootstrap/css/bootstrap.min.css',  //useDarkMode ? 'dark' : 'default',
            content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
            relative_urls: false, 
            convert_urls: false, 
            remove_script_host: false,
            valid_elements : '*[*]',
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });


        function SetThumbnail(fileUrl) {
            $('#background_image').val(fileUrl);
            $('#iLogo').attr('src', fileUrl);
        }

   

        $.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            },
            "输入的格式不正确，只支持小写英文与下划线输入！"
        );



        $(document).ready(function () {
            //当前菜单
            $("#module_nav>li:nth-of-type(1)").addClass("active").siblings().removeClass('active');        
            $(".mainmenu>li.pages a").addClass("active");
 

            $("#btnBrowser").on("click", function () {
                singleEelFinder.selectActionFunction = SetThumbnail;
                singleEelFinder.open();
            });

            $("#btnImgDelete").on("click", function() {
                $('#background_image').val("");
                $('#iLogo').attr('src', $('#iLogo').attr('data-default-src'));
                var myImage = document.getElementById('iLogo');
                Holder.run({
                    images: myImage
                });
            });


            $("#editform").validate({

                rules: {
                    title: {
                        required: true,
                        maxlength: 150
                    },
                    // alias: {
                    //     required: true,
                    //     maxlength: 100,
                    //     regex:"^[a-z0-9_-]+$",
                    //     remote: {
                    //         url: "page_post.php",
                    //         type: "post",
                    //         dataType: "JSON",
                    //         data: {
                    //             id: function () {
                    //                 return $("#id").val();
                    //             },
                    //             alias: function () {
                    //                 return $("#alias").val();
                    //             },
                    //             action:function(){
                    //                 return 'checkcode';
                    //             }
                    //         },
                    //         dataFilter: function (data) {
                    //             if (data==="0") {
                    //                 // jquery validate remote method
                    //                 // accepts only "true" value
                    //                 // to successfully validate field 
                    //                 return '"true"';
                    //             } else {
                    //                 // error message, everything that isn't "true"
                    //                 // is understood as failure message
                    //                 return '"别名已存在！"';
                    //             }
                    //         }
                    //     }
                    // }
                },
                messages: {
                    title: {
                        required: "请输入主标题",
                        maxlength: "不能超过150个字符"
                    },
                    // alias: {
                    //     required: "请输入别名",
                    //     maxlength: "不能超过100个字符"
                    // }

                },

                errorClass: "invalid-feedback",
                errorElement: "div",
                highlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-valid');
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                    $(element).addClass('is-valid');
                },
                submitHandler: function (form) {
                  
                    $.ajax({
                        url: '/pages/update',
                        type: 'POST',
                        // data: values,
                        data: $(form).serialize(),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function (res) {
                            //  $('#resultreturn').prepend(res);
                            var myobj = JSON.parse(res);                    
                            //console.log(myobj.status);
                            if (myobj.status === 1) {
                                toastr.success(myobj.message);                                        
                            } 
                            if (myobj.status === 2) {
                                toastr.error(myobj.message)
                            }
                            if (myobj.status === 3) {
                                toastr.info(myobj.message)
                            }
                        }
                    });


                }
            });
        });
    </script>
{% endblock %}
